package com.util;

import com.pojo.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
@Component("dateAdvice")
@Aspect
public class DateAdvice {
    @Before("execution(* com.service.impl.*.add*(..))")
    public void Add(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        /**
         * 获取入参
         */
        Object[] objects =joinPoint.getArgs();
        /**
         * 根据入参获得session并获取当前登录用户
         */
        HttpSession session=TlManager.getSessionTl();
        User loginUser= (User) session.getAttribute("loginUser");

        Class entity=objects[0].getClass();
        Object duixiang = objects[0];

        Method m1=entity.getDeclaredMethod( "setCreateDate",Date.class);
        m1.invoke(duixiang,new Date());

        Method m2=entity.getDeclaredMethod("setCreateBy",String.class);
        m2.invoke(duixiang,loginUser.getUserName());

    }

    @Before("execution(* com.service.impl.*.update*(..))")
    public void Update(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        /**
         * 获取入参
         */
        Object[] objects =joinPoint.getArgs();
        /**
         * 根据入参获得session并获取当前登录用户
         */
        HttpSession session=TlManager.getSessionTl();
        User loginUser= (User) session.getAttribute("loginUser");

        Class entity=objects[0].getClass();
        Object duixiang = objects[0];

        Method m1=entity.getDeclaredMethod( "setUpdateDate",Date.class);
        m1.invoke(duixiang,new Date());

        Method m2=entity.getDeclaredMethod("setUpdateBy",String.class);
        m2.invoke(duixiang,loginUser.getUserName());

    }
}
